package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.adapter.MyOnScroll;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.MyCollectionBean;
import com.example.administrator.szb.bean.RzBean;
import com.example.administrator.szb.bean.SCBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/9/27.
 */

public class MyCollectionActivity extends BaseActivity {
    @Bind(R.id.my_collection_bsfh)
    ImageView myCollectionBsfh;
    @Bind(R.id.my_collection_bj)
    TextView myCollectionFb;
    @Bind(R.id.my_collection_hd)
    RadioButton myCollectionHd;
    @Bind(R.id.my_collection_zx)
    RadioButton myCollectionZx;
    @Bind(R.id.my_collection_radiogroup)
    RadioGroup myCollectionRadiogroup;
    @Bind(R.id.my_collection_recyclerview)
    RecyclerView myCollectionRecyclerview;
    @Bind(R.id.my_collection_qx)
    TextView myCollectionQx;
    @Bind(R.id.my_collection_sc)
    TextView myCollectionSc;
    @Bind(R.id.my_collection_ll)
    LinearLayout myCollectionLl;
    private int current_page = 1;
    private int per_page = 10;
    int type = 1;//1,问答，2，资讯
    MyCollectionBean mYcollectionbean;
    ArrayList<MyCollectionBean.DataBean.ReferBean> mdata = new ArrayList<>();
    ArrayList<MyCollectionBean.DataBean.Article> mdata_zx = new ArrayList<>();
    BaseAdapter<MyCollectionBean.DataBean.ReferBean> adapter;
    BaseAdapter<MyCollectionBean.DataBean.Article> adapter_zx;
    ArrayList<String> refer_id = new ArrayList<String>(){
        @Override
        public String toString() {
            String s= "";
            for (String info: refer_id) {
                s = s+ info+",";
            }
            return s;
        }
    };

    ArrayList<String> refer_id_zx = new ArrayList<String>(){
        @Override
        public String toString() {
            String s= "";
            for (String info: refer_id_zx) {
                s = s+ info+",";
            }
            return s;
        }
    };
    private View footerview;
    View error_head;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_collection_activity);
        SampleApplicationLike.getActivitiesInstance().add(this);
        ButterKnife.bind(this);
        footerview = LayoutInflater.from(this).inflate(R.layout.view_wd_footer, null);
        footerview.setVisibility(View.INVISIBLE);
        requsetMyCollection();
        initListener();

    }

    private void initListener() {
        myCollectionRadiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i){
                    case R.id.my_collection_hd:
                        type = 1;
                        if (adapter != null)
                        myCollectionRecyclerview.setAdapter(adapter);
                        break;
                    case R.id.my_collection_zx:
                        type = 2;
                        if (adapter != null)
                        myCollectionRecyclerview.setAdapter(adapter_zx);
                        break;
                }
            }
        });
    }

    /**
     * 收藏请求
     */
    private void requsetMyCollection() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("current_page",current_page+"");
        map.put("per_page",per_page+"");
        String url = URLAddress.URLBASE + URLAddress.URL_COLLECTION;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, MyCollectionBean.class, URLAddress.URLBASE + URLAddress.URL_COLLECTION, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                mYcollectionbean = (MyCollectionBean) response;
                if (mYcollectionbean.getResult() == 1 && current_page == 1){
                    mdata.addAll(mYcollectionbean.getData().getRefer());
                    mdata_zx.addAll(mYcollectionbean.getData().getArticle());
                    current_page = current_page + 1;
                    initView();
                }else if(mYcollectionbean.getResult() == 1){
                    current_page = current_page + 1;
                    mdata.addAll(mYcollectionbean.getData().getRefer());
                    mdata_zx.addAll(mYcollectionbean.getData().getArticle());
                    adapter.notifyDataSetChanged();
                    footerview.setVisibility(View.INVISIBLE);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                footerview.setVisibility(View.INVISIBLE);
                Toasts.show(MyCollectionActivity.this, "没有数据了", Toast.LENGTH_SHORT);
            }
        });
    }

    private void initView() {
        adapter = new BaseAdapter<MyCollectionBean.DataBean.ReferBean>(this,mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, MyCollectionBean.DataBean.ReferBean referBean) {
                initItem(position,holder,referBean);
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_my_collection_item;
            }
        };
        adapter_zx = new BaseAdapter<MyCollectionBean.DataBean.Article>(this,mdata_zx) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final MyCollectionBean.DataBean.Article listBean) {
                ((CheckBox)holder.getView(R.id.checkBox5)).setChecked(listBean.isChoose());
                if (listBean.getIsShowCheckBod() == View.VISIBLE){
                    ((CheckBox)holder.getView(R.id.checkBox5)).setVisibility(View.VISIBLE);
                }else{
                    ((CheckBox)holder.getView(R.id.checkBox5)).setVisibility(View.GONE);
                }

                ((CheckBox)holder.getView(R.id.checkBox5)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            mdata_zx.get(position).setChoose(true);
                           refer_id_zx.add(listBean.getId()+"");
                        }else{
                            mdata_zx.get(position).setChoose(false);
                            refer_id_zx.remove(listBean.getId()+"");
                        }
                    }
                });


                //initItem(holder,referBean);
                ((TextView)holder.getView(R.id.textView58)).setText(listBean.getAuthor());
                ((TextView)holder.getView(R.id.textView59)).setText(listBean.getCreate_time());
                ((TextView)holder.getView(R.id.textView162)).setText(listBean.getTitle());
                if(listBean.getType() == 1){
                    (holder.getView(R.id.imageView24)).setVisibility(View.GONE);
                }else{
                    (holder.getView(R.id.imageView24)).setVisibility(View.VISIBLE);
                }

                ((TextView)holder.getView(R.id.textView163)).setText(listBean.getCollect_count()+"人浏览");

                if (TextUtils.isEmpty(listBean.getImage())) {
                    (holder.getView(R.id.imageView23)).setVisibility(View.GONE);
                }else{
                    Glide.with(MyCollectionActivity.this).load(listBean.getImage()).into(((ImageView)holder.getView(R.id.imageView23)));
                }

                if (!TextUtils.isEmpty(listBean.getHeadImg())){
                    Glide.with(MyCollectionActivity.this).load(listBean.getHeadImg()).into(((ImageView)holder.getView(R.id.imageView22)));
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zx_item;
            }
        };

        /**
         * 添砖到问题详情，回答问题
         */
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(MyCollectionActivity.this, WTContentActivity.class);
                //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                intent.putExtra("refer_id",mdata.get(position).getId());
                startActivity(intent);
            }
        });


        loadMore();
        myCollectionRecyclerview.setLayoutManager(new LinearLayoutManager(MyCollectionActivity.this));
        if (mdata.size() == 0){
            error_head = LayoutInflater.from(MyCollectionActivity.this).inflate(R.layout.view_item_error, myCollectionRecyclerview, false);
            adapter.addHeaderView(error_head);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("尚未收藏任何问答");
        }else{
            adapter.addFootView(footerview);
        }

        if (mdata_zx.size() == 0){
            error_head = LayoutInflater.from(MyCollectionActivity.this).inflate(R.layout.view_item_error, myCollectionRecyclerview, false);
            adapter_zx.addHeaderView(error_head);
            ((TextView)error_head.findViewById(R.id.text_view_error)).setText("尚未收藏任何资讯");
        }else{
            adapter_zx.addFootView(footerview);
        }




        if (type == 1){
            myCollectionRecyclerview.setAdapter(adapter);
        }else if (type == 2){
            myCollectionRecyclerview.setAdapter(adapter_zx);
        }
       // type == 1 ? myCollectionRecyclerview.setAdapter(adapter_zx) : myCollectionRecyclerview.setAdapter(com.example.administrator.szb.adapter);


    }

    /**
     * 开启加载更多
     */
    private void loadMore() {

        myCollectionRecyclerview.addOnScrollListener(new MyOnScroll(){
            @Override
            public void scrollBottom() {

                super.scrollBottom();
                footerview.setVisibility(View.VISIBLE);
                requsetMyCollection();
            }
        });
    }



    private void initItem(final int position, final BaseAdapter<MyCollectionBean.DataBean.ReferBean>.BaseViewHolder holder, final MyCollectionBean.DataBean.ReferBean referBean) {
        ((CheckBox)holder.getView(R.id.checkBox3)).setChecked(referBean.getIsChoose());
        if (referBean.getIsShowCheckBod() == View.VISIBLE){
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.VISIBLE);
        }else{
            ((CheckBox)holder.getView(R.id.checkBox3)).setVisibility(View.GONE);
        }

        ((CheckBox)holder.getView(R.id.checkBox3)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mdata.get(position).setIsChoose(true);
                    refer_id.add(referBean.getId()+"");
                }else{
                    mdata.get(position).setIsChoose(false);
                    refer_id.remove(referBean.getId()+"");
                }
            }
        });

        /**
         * todo 填充数据
         */
        ((TextView)holder.getView(R.id.textView63)).setText(referBean.getTitle());
        ((TextView)holder.getView(R.id.textView64)).setText(referBean.getCollect_count()+"收藏");
        ((TextView)holder.getView(R.id.textView65)).setText(referBean.getReply()+"回答");
        ((TextView)holder.getView(R.id.textView66)).setText(referBean.getCreate_time());
    }

    @OnClick({R.id.my_collection_bsfh, R.id.my_collection_bj, R.id.my_collection_qx, R.id.my_collection_sc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_collection_bsfh:
                finish();
                break;
            case R.id.my_collection_bj:

                try{
                    if (((TextView)view).getText().toString().equals("编辑")) {
                        ((TextView)view).setText("取消");
                        myCollectionLl.setVisibility(View.VISIBLE);
                        for (int i = 0; i < mdata.size(); i++) {
                            mdata.get(i).setIsShowCheckBod(View.VISIBLE);
                        }

                        for (int i = 0; i < mdata_zx.size(); i++) {
                            mdata_zx.get(i).setIsShowCheckBod(View.VISIBLE);
                        }

                    }else{
                        myCollectionRecyclerview.setClickable(true);
                        adapter.isClickable(new BaseAdapter.IsClickable() {
                            @Override
                            public boolean isClickable() {
                                return true;
                            }
                        });
                        adapter_zx.isClickable(new BaseAdapter.IsClickable() {
                            @Override
                            public boolean isClickable() {
                                return true;
                            }
                        });
                        ((TextView)view).setText("编辑");
                        myCollectionLl.setVisibility(View.GONE);
                        for (int i = 0; i < mdata.size(); i++) {
                            mdata.get(i).setIsShowCheckBod(View.GONE);
                        }

                        for (int i = 0; i < mdata_zx.size(); i++) {
                            mdata_zx.get(i).setIsShowCheckBod(View.GONE);
                        }
                    }



                    adapter.notifyDataSetChanged();
                    adapter_zx.notifyDataSetChanged();
                }catch (Exception e){

                }


                break;
            case R.id.my_collection_qx:

                try{
                    if (((TextView)view).getText().toString().equals("全选")) {
                        ((TextView)view).setText("全不选");
                        for (int i = 0; i < mdata.size(); i++) {
                            mdata.get(i).setIsChoose(true);
                        }

                        for (int i = 0; i < mdata_zx.size(); i++) {
                            mdata_zx.get(i).setChoose(true);
                        }
                    }else{
                        ((TextView)view).setText("全选");
                        for (int i = 0; i < mdata.size(); i++) {
                            mdata.get(i).setIsChoose(false);
                        }
                        for (int i = 0; i < mdata_zx.size(); i++) {
                            mdata_zx.get(i).setChoose(false);
                        }
                    }


                    adapter_zx.notifyDataSetChanged();
                    adapter.notifyDataSetChanged();
                }catch (Exception e){

                }

                break;
            case R.id.my_collection_sc:
                //refer_id.toString();
                if (type == 1){
                    requestDelWD();//执行取消收藏操作
                }else {
                    requestCancleCollection();
                }

                break;
        }
    }

    private void requestCancleCollection() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("article_id",refer_id_zx.toString());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, SCBean.class, URLAddress.URLBASE + URLAddress.URL_QXSCZX, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                SCBean rZBean = (SCBean) response;
                if (rZBean.getResult() == 1){
                    startActivity(new Intent(MyCollectionActivity.this,MyCollectionActivity.class));
                    finish();
                }else {
                    Toasts.show(MyCollectionActivity.this, "没得数据呀", Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toasts.show(MyCollectionActivity.this, ""+error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }

    /**
     * 取消收藏
     */
    private void requestDelWD() {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("refer_id",refer_id.toString());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, RzBean.class, URLAddress.URLBASE + URLAddress.URL_CANCLE_COLLECTION, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                RzBean rZBean = (RzBean) response;
                if (rZBean.getResult() == 1){
                    startActivity(new Intent(MyCollectionActivity.this,MyCollectionActivity.class));
                    finish();
                }else {
                    Toasts.show(MyCollectionActivity.this, "没得数据呀", Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Toasts.show(MyCollectionActivity.this, ""+error.toString(), Toast.LENGTH_SHORT);
            }
        });
    }

}
